package com.estore.network;

import com.com.estore02.model.Product;
import com.com.estore02.service.ProductSorters;
import java.io.*;
import java.net.Socket;
import java.util.*;

/**
 * 商城客户端 - 通过网络连接访问服务器
 */
public class EStoreClient {
    private final String serverHost;
    private final int serverPort;
    private final Scanner scanner;
    private Map<String, Integer> shoppingCart;

    public EStoreClient(String host, int port) {
        this.serverHost = host;
        this.serverPort = port;
        this.scanner = new Scanner(System.in);
        this.shoppingCart = new HashMap<>();
    }

    /**
     * 向服务器发送请求并获取响应
     */
    private Object sendRequest(String request) {
        try (Socket socket = new Socket(serverHost, serverPort);
             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream input = new ObjectInputStream(socket.getInputStream())) {

            output.writeObject(request);
            output.flush();

            return input.readObject();

        } catch (IOException | ClassNotFoundException e) {
            System.out.println("❌ 网络错误: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取所有商品
     */
    @SuppressWarnings("unchecked")
    private List<Product> getAllProducts() {
        Object response = sendRequest("GET_ALL_PRODUCTS");
        if (response instanceof List) {
            return (List<Product>) response;
        } else {
            System.out.println("❌ 获取商品失败: " + response);
            return new ArrayList<>();
        }
    }

    /**
     * 根据ID获取商品
     */
    private Product getProductById(String productId) {
        Object response = sendRequest("GET_PRODUCT:" + productId);
        if (response instanceof Product) {
            return (Product) response;
        } else {
            System.out.println("❌ 获取商品失败: " + response);
            return null;
        }
    }

    /**
     * 启动客户端
     */
    public void start() {
        System.out.println("🛒 欢迎来到电子商城客户端");
        System.out.println("🌐 服务器: " + serverHost + ":" + serverPort);

        // 测试连接
        Object testResponse = sendRequest("GET_PRODUCT_COUNT");
        if (testResponse == null) {
            System.out.println("❌ 无法连接到服务器，请检查服务器是否启动");
            return;
        }

        System.out.println("✅ 服务器连接成功");

        while (true) {
            showMenu();
            String input = scanner.nextLine();

            if (!isValidChoice(input, 1, 7)) {
                System.out.println("❌ 无效的选择，请重新输入！");
                continue;
            }

            int choice = Integer.parseInt(input);

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    browseProductsWithSort();
                    break;
                case 3:
                    searchProduct();
                    break;
                case 4:
                    addToCart();
                    break;
                case 5:
                    viewCart();
                    break;
                case 6:
                    checkout();
                    break;
                case 7:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n========== 商城客户端菜单 ==========");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 排序浏览商品");
        System.out.println("3. 搜索商品");
        System.out.println("4. 添加到购物车");
        System.out.println("5. 查看购物车");
        System.out.println("6. 结算");
        System.out.println("7. 退出");
        System.out.println("===================================");
        System.out.print("请输入您的选择: ");
    }

    /**
     * 浏览商品
     */
    private void browseProducts() {
        List<Product> products = getAllProducts();
        displayProducts(products, "默认排序");
    }

    /**
     * 排序浏览商品
     */
    private void browseProductsWithSort() {
        while (true) {
            System.out.println("\n-------- 选择排序方式 --------");
            System.out.println("1. 按价格从低到高");
            System.out.println("2. 按价格从高到低");
            System.out.println("3. 按库存从多到少");
            System.out.println("4. 按商品名称排序");
            System.out.println("5. 返回主菜单");
            System.out.println("-----------------------------");
            System.out.print("请选择排序方式: ");

            String input = scanner.nextLine();
            if (!isValidChoice(input, 1, 5)) {
                System.out.println("❌ 无效的选择，请重新输入！");
                continue;
            }

            int sortChoice = Integer.parseInt(input);

            if (sortChoice == 5) {
                break;
            }

            List<Product> products = getAllProducts();
            String sortType = applySorting(products, sortChoice);
            displayProducts(products, sortType);
        }
    }

    /**
     * 应用排序
     */
    private String applySorting(List<Product> products, int sortChoice) {
        switch (sortChoice) {
            case 1:
                products.sort(ProductSorters.BY_PRICE_ASC);
                return "价格从低到高";
            case 2:
                products.sort(ProductSorters.BY_PRICE_DESC);
                return "价格从高到低";
            case 3:
                products.sort(ProductSorters.BY_STOCK_DESC);
                return "库存从多到少";
            case 4:
                products.sort(ProductSorters.BY_NAME_ASC);
                return "商品名称排序";
            default:
                return "默认排序";
        }
    }

    /**
     * 显示商品列表
     */
    private void displayProducts(List<Product> products, String sortType) {
        System.out.println("\n--- 商品列表 (" + sortType + ") ---");
        if (products.isEmpty()) {
            System.out.println("暂无商品！");
            return;
        }

        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            String stockInfo = product.getStock() > 0 ?
                    String.valueOf(product.getStock()) : "【售罄】";
            System.out.printf("%d. ID: %-5s | 名称: %-20s | 价格: ¥%-8.2f | 库存: %s%n",
                    i + 1, product.getId(), product.getName(), product.getPrice(), stockInfo);
        }

        int availableCount = (int) products.stream().filter(p -> p.getStock() > 0).count();
        System.out.printf("【商品总数: %d | 有库存: %d】%n", products.size(), availableCount);
    }

    /**
     * 搜索商品
     */
    private void searchProduct() {
        System.out.print("请输入商品ID或名称关键字：");
        String keyword = scanner.nextLine().toLowerCase();

        List<Product> allProducts = getAllProducts();
        List<Product> results = new ArrayList<>();

        for (Product product : allProducts) {
            if (product.getId().toLowerCase().contains(keyword) ||
                    product.getName().toLowerCase().contains(keyword)) {
                results.add(product);
            }
        }

        if (results.isEmpty()) {
            System.out.println("未找到相关商品！");
        } else {
            displayProducts(results, "搜索结果");
        }
    }

    /**
     * 添加到购物车
     */
    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine().trim();

        Product product = getProductById(productId);
        if (product == null) {
            System.out.println("❌ 错误：商品不存在！");
            return;
        }

        System.out.println("📦 商品信息: " + product);

        if (product.getStock() <= 0) {
            System.out.println("❌ 抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量 (库存 " + product.getStock() + "): ");
        String quantityInput = scanner.nextLine();

        if (!isValidNumber(quantityInput)) {
            System.out.println("❌ 错误：请输入有效的正整数！");
            return;
        }

        int quantity = Integer.parseInt(quantityInput);

        if (quantity <= 0) {
            System.out.println("❌ 错误：购买数量必须为正数！");
            return;
        }

        if (quantity > product.getStock()) {
            System.out.println("❌ 错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        int currentQuantity = shoppingCart.getOrDefault(productId, 0);
        shoppingCart.put(productId, currentQuantity + quantity);
        System.out.println("✅ 成功将 " + quantity + " 件 '" + product.getName() + "' 添加到购物车！");
    }

    /**
     * 查看购物车
     */
    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("🛒 购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        int itemCount = 0;

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = getProductById(productId);

            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("📦 商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                itemCount += quantity;
            }
        }

        System.out.println("----------------------------------------");
        System.out.printf("🛍️  商品总数: %d 件\n", itemCount);
        System.out.printf("💰 总计: ¥%.2f\n", total);
    }

    /**
     * 结算功能
     */
    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("❌ 购物车为空，无法结算！");
            return;
        }

        viewCart();

        System.out.print("\n确认结算？(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if (!confirm.equals("y") && !confirm.equals("yes")) {
            System.out.println("💡 已取消结算");
            return;
        }

        // 验证库存
        boolean allStockSufficient = true;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = getProductById(productId);

            if (product != null && quantity > product.getStock()) {
                System.out.println("❌ 错误：商品 '" + product.getName() + "' 库存不足！");
                System.out.println("   所需: " + quantity + "，当前库存: " + product.getStock());
                allStockSufficient = false;
            }
        }

        if (!allStockSufficient) {
            System.out.println("💡 请调整购物车中的商品数量后重新结算");
            return;
        }

        System.out.println("✅ 结算成功！感谢您的购买！");
        shoppingCart.clear();
    }

    /**
     * 验证选择是否有效
     */
    private boolean isValidChoice(String input, int min, int max) {
        if (input == null || input.trim().isEmpty()) {
            return false;
        }
        try {
            int choice = Integer.parseInt(input.trim());
            return choice >= min && choice <= max;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 验证输入是否为有效数字
     */
    private boolean isValidNumber(String input) {
        if (input == null || input.trim().isEmpty()) {
            return false;
        }
        try {
            int number = Integer.parseInt(input.trim());
            return number > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8888;

        if (args.length >= 2) {
            host = args[0];
            try {
                port = Integer.parseInt(args[1]);
            } catch (NumberFormatException e) {
                System.out.println("⚠️  无效端口号，使用默认端口: 8888");
            }
        }

        EStoreClient client = new EStoreClient(host, port);
        client.start();
    }
}